package com.sprite.utils.http.payload;

import com.sprite.utils.UtilString;
import com.sprite.utils.http.ContentType;
import com.sprite.utils.http.RequestPayload;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 表单数据,
 * content type : application/x-www-form-urlencoded
 *
 * @author Jackl
 * @since 1.2.4
 */
public class FormData implements RequestPayload {

    private ContentType contentType = new ContentType("application/x-www-form-urlencoded; charset=" + Charset.defaultCharset().name());

    public LinkedHashMap<String, Object> parameter = new LinkedHashMap<>();

    @Override
    public void writePayload(OutputStream outputStream) throws IOException {
        String paramCharset = getCharset();

        if (paramCharset != null) {
            paramCharset = Charset.defaultCharset().name();
        }

        StringBuilder finalUrl = new StringBuilder();
        for (Map.Entry<String, Object> param : parameter.entrySet()) {
            finalUrl.append(param.getKey()).append("=").append(URLEncoder.encode(UtilString.toString(param.getValue()), paramCharset)).append("&");
        }
        finalUrl.deleteCharAt(finalUrl.length() - 1);

        outputStream.write(finalUrl.toString().getBytes());
    }

    /**
     * 添加表单参数
     *
     * @param key
     *         param name
     * @param value
     *         param value
     */
    public void putParam(String key, Object value) {
        if (value == null) {
            return;
        }
        parameter.put(key, value);
    }

    /**
     * 获取表单参数
     *
     * @param key
     *         param name
     * @return param value
     */
    public Object getParam(String key) {
        return parameter.get(key);
    }

    public void setCharset(String charset) {
        contentType.putParam("charset", charset);
    }

    public String getCharset() {
        return contentType.getCharset();
    }

    /**
     * 获取 content type
     *
     * @return
     */
    @Override
    public ContentType getContentType() {
        return this.contentType;
    }

}
